<?php
/*
 * 阿里体育
 */
require FILE . 'lib/alibaba/TopSdk.php';
class alibabaModel{
    private $c;
    private $appkey;
    public function __construct(& $base){
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
        
        $this->c = new TopClient;
        $this->c->appkey = $this->base->config['alibaba_sports']['AppKey'];
        $this->c->secretKey = $this->base->config['alibaba_sports']['AppSecret'];
        $this->appkey = $this->base->config['alibaba_sports']['AppKey'];
        $this->secretKey = $this->base->config['alibaba_sports']['AppSecret'];
        $this->host = 'http://wora.alisports.com/wora-job/api';
    }
    
    private function initBaichuan(){
        $this->c->appkey = $this->base->config['alibaba_baichuan']['AppKey'];
        $this->c->secretKey = $this->base->config['alibaba_baichuan']['AppSecret'];
        $this->appkey = $this->base->config['alibaba_baichuan']['AppKey'];
        $this->secretKey = $this->base->config['alibaba_baichuan']['AppSecret'];
        $this->host = '';
    }

	private function sportsGenerateSign($params)
	{
		ksort($params);

		$stringToBeSigned = $this->secretKey;
		foreach ($params as $k => $v)
		{
			if(is_string($v) && "@" != substr($v, 0, 1))
			{
				$stringToBeSigned .= "$k$v";
			}
		}
		unset($k, $v);
		$stringToBeSigned .= $this->secretKey;

		return md5($stringToBeSigned);
	}
    
    /*
     * 验证
     */
    public function verify($appkey,$md5,$method='post'){
        if($appkey && $appkey != $this->appkey){
            return false;
        }
        
        $params = $method == 'post' ? $_POST : $_GET;
        unset($params['md5']);
        if($this->sportsGenerateSign($params) != $md5){
            //return false;
        }
        return true;
    }
    
    /*
     * 绑定用户
     */
    public function bind($data){
        $row['uid'] = $data['uid'];
        $row['partner_name'] = 'alibaba_sports';
        $row['partner_uid'] = $data['partner_uid'];
        $row['partner_eid'] = isset($data['partner_eid']) ? $data['partner_eid'] : '';
        $row['addtime'] = isset($data['addtime']) ? $data['addtime'] : time();
        $this->db->insertRowTable('r_partner_user',$row);
    }
    
    /*
     * entrollCallback
     */
    public function updateMember($userInfo){
        $url = $this->host.'/member/updatemember';
        $params = [
            'userid' => (string)$userInfo['uid'],
            'aliuid' => (string)$userInfo['partner_uid'],
            'appkey' => $this->appkey,
            'real_name' => '',
            'sex' => $userInfo['gender']==0 ? '1' : '2',
            'mobile' => $userInfo['phone'],
            'certi_number' => '',
            'email' => ''
        ];
        $params['md5'] = $this->sportsGenerateSign($params);
        $res = $this->c->curl($url,$params);
    }
    
    /*
     * 向阿里发送跑步信息
     */
    public function addData($data){
        $uid = $data['uid'];
        $partner_user = $this->getUserInfo($uid);
        if(!$partner_user){
            return;
        }
        $coordinate = $data['coordinate'];
        $run_start = $coordinate[0][0];
        $run_end = end($coordinate);
        $run_end = end($run_end);
        $url = $this->host.'/sign/adddata';
        $params = [
            'userid' => (string)$uid,
            'aliuid' => (string)$partner_user['partner_uid'],
            'appkey' => $this->appkey,
            'activityid' => (string)$data['did'],
            'run_start_time' => (string)($data['updatetime']-$data['elapsedtime']),
            'run_end_time' => (string)$data['updatetime'],
            'distance' => (string)(int)($data['mileage']*1000),
            'calorie' => (string)(int)$data['calorie'],
            'steps' => (string)(int)($data['detail_footsteps']*$data['elapsedtime']/60),
            'run_start_latitude' => $run_start['lat'],
            'run_start_longtitude' => $run_start['lng'],
            'run_end_latitude' => $run_end['lat'],
            'run_end_longtitude' => $run_end['lng'],
        ];
        $params['md5'] = $this->sportsGenerateSign($params);
        $this->c->curl($url,$params);
    }
    
    /**
     * 获取参与用户
     */
    public function getUserInfo($uid){
        return $this->db->getRowTable('r_partner_user',array(),"partner_name='alibaba_sports' and uid = '{$uid}'");
    }
    
    /*
     * 获得参赛信息
     */
    public function getAddInfo($uid){
        return $this->db->getAll("select * from r_partner_user where partner_name='alibaba_sports' and uid='{$uid}'");
    }
    
    /*
     * 获得对方用户信息
     */
    public function getCoins($uid){
        $user = $this->getUserInfo($uid);
        if(!$user){
            return false;
        }
        
        $url = 'http://wora.alisports.com/api/coupon/getCoins';
        $params = [
            'aliuid' => $user['partner_uid'],
            'appkey' => $this->appkey
        ];
        $md5 = $this->sportsGenerateSign($params);
        $url .= "?aliuid={$user['partner_uid']}&appkey={$this->appkey}&md5={$md5}";
        $res = $this->c->curl($url);
        if(!$res){
            return false;
        }
        $res = json_decode($res,true);
        if($res['res_code'] != 1){
            return false;
        }
        $user['ca_money'] = $res['data']['ca_money'];
        $user['tao_coins'] = $res['data']['tao_coins'];
        $redisKey = REDIS_PREFIX.'PartnerUserInfo_'.$uid;
        $this->redis->hmset($redisKey,$user);
        $this->redis->expire($redisKey,7200);
        return $user;
    }
    
    /*
     * 添加百川聊天用户
     */
    public function addOpenImUser($data){
        $this->initBaichuan();
        if(!isset($this->req)){
            $this->req = new OpenimUsersAddRequest;
        }
        $userinfos = new Userinfos;
        $userinfos->nick = $data['nick'];
        $userinfos->icon_url = $data['icon_url'];
        $userinfos->email = '';
        $userinfos->mobile = '';
        $userinfos->userid = $data['userid'];
        $userinfos->password = $data['password'];
        $this->req->setUserinfos(json_encode($userinfos));
        $resp = $this->c->execute($this->req);
        return $resp;
    }
    
    /*
     * 更新百川聊天用户
     */
    public function updateOpenImUser($data){
        $this->initBaichuan();
        if(!isset($this->req)){
            $this->req = new OpenimUsersUpdateRequest;
        }
        $userinfos = new Userinfos;
        $userinfos->nick = $data['nick'];
        $userinfos->icon_url = $data['icon_url'];
        $userinfos->email = '';
        $userinfos->mobile = '';
        $userinfos->userid = $data['userid'];
        $userinfos->password = $data['password'];
        $this->req->setUserinfos(json_encode($userinfos));
        $resp = $this->c->execute($this->req);
        return $resp;
    }
    
    /*
     * 获得百川用户
     */
    public function getOpenImUser($id){
        $this->initBaichuan();
        $req = new OpenimUsersGetRequest;
        $req->setUserids($id);
        return $this->c->execute($req);
    }
}